/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.zprofilefrontend.common.Util;
import com.vng.zing.zprofilefrontend.common.Validation;
import com.vng.zing.calc.thrift.GENDER;
import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import com.vng.zing.zcommon.thrift.PutPolicy;
import static com.vng.zing.zprofilefrontend.model.BaseModel.checkLogIn;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 *
 * @author namhh
 */
public class AjaxUpdateModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(LogInModel.class);
    public static final AjaxUpdateModel Instance = new AjaxUpdateModel();

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        ThreadProfiler profiler = Profiler.getThreadProfiler();
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            ///TODO..
            profiler.push(this.getClass(), "output");
             ProfileSession profileSession = checkLogIn(req);
            String value = "";
            if (null == profileSession) {
                out.println(Util.toJSON("ERROR", "Update profile failed."));
            } else {
                Map<String, Object> validateRes;
                if (null == req.getParameter("profile")) {
                    validateRes = validateProfileField(req);
                } else {
                    validateRes = validateProfile(req.getParameter("profile"));
                }
                if ("SUCCESS".equals(validateRes.get("STATUS"))) {
                    Profile oldProfile = getClientWithCache().getaLoad(profileSession.getId());
                    if (null == req.getParameter("profile")) {
                        
                        if (null != validateRes.get("displayName")) {
                            oldProfile.setDisplayName((String) validateRes.get("displayName"));
                            value = (null != oldProfile.getDisplayName() && !"".equals(oldProfile.getDisplayName()) ? oldProfile.getDisplayName() : oldProfile.getUsername());
                        }
                        if (null != validateRes.get("email")) {
                            oldProfile.setEmail((String) validateRes.get("email"));
                        }
                        if (null != validateRes.get("dateOfBirth")) {
                            oldProfile.setDateOfBirth((Integer) validateRes.get("dateOfBirth"));
                            Long now = new Date().getTime() / 1000;
                            long age = (now.intValue() - oldProfile.getDateOfBirth()) / (3600 * 24 * 365);
                            value = String.format("%s", age);
                        }

                        if (null != validateRes.get("mobile")) {
                            oldProfile.setMobileNumber((String) validateRes.get("mobile"));
                        }
                        if (null != validateRes.get("gender")) {
                            oldProfile.setGender(GENDER.findByValue((Short) validateRes.get("gender")));
                            value = oldProfile.getGender().name();
                        }
                        if (null != validateRes.get("cityId")) {
                            oldProfile.setCityId((Short) validateRes.get("cityId"));
                            value = CityModel.getInstance().getAllCities().get(oldProfile.getCityId());
                        }
                    } else {
                        Profile newprofile = (Profile) validateRes.get("MESSAGE");
                        oldProfile.setDisplayName(newprofile.getDisplayName());
                        oldProfile.setCityId(newprofile.getCityId());
                        oldProfile.setDateOfBirth(newprofile.getDateOfBirth());
                        oldProfile.setGender(newprofile.getGender());
                        oldProfile.setMobileNumber(newprofile.getMobileNumber());
                        oldProfile.setEmail(newprofile.getEmail());
                    }
                    oldProfile.setModifiedBy(oldProfile.getUsername());
                    Long modifiedDate = (new Date().getTime() / 1000);
                    oldProfile.setModifiedDate(modifiedDate.intValue());
                    oldProfile = getClient().updateProfile(oldProfile);
                    if (null != oldProfile) {
                        getClientWithCache().putCache(oldProfile.getId(), oldProfile, PutPolicy.ADD_OR_UDP);
                        setLoggedIn(req, resp, new ProfileSession(oldProfile.getId()), false);
                        out.println(Util.toJSON("SUCCESS", "info?id="+oldProfile.getId(),value));
                    } else {
                        out.println(Util.toJSON("ERROR", getProperties().get("en.update.failed")));
                    }
                } else {
                    out.println(JSONObject.toJSONString(validateRes));
                }
            }
            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private Map<String, Object> validateProfileField(HttpServletRequest req) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {

            String message = "";

            if (null != req.getParameter("displayName")) {
                String displayName = (String) req.getParameter("displayName");
                if (Validation.validateDisplayName(displayName)) {
                    ret.put("displayName", displayName);
                } else {
                    message += getProperties().get("en.INVALID_DISPLAYNAME");
                }
            } else {

            }

            if (null != req.getParameter("email")) {
                String email = (String) req.getParameter("email");
                if (Validation.validateEmail(email)) {
                    ret.put("email", email);
                } else {
                    message += getProperties().get("en.INVALID_EMAIL");
                }
            } else {
            }

            if (null != req.getParameter("cityId") || Util.isShort((String) req.getParameter("cityId"))) {
                Short cityId = Short.parseShort((String) req.getParameter("cityId"));
                if (null == CityModel.getInstance().getAllCities().get(cityId)) {
                    message += getProperties().get("en.INVALID_CITY");
                } else {
                    ret.put("cityId", cityId);
                }
            } else {

            }

            if (null != req.getParameter("dateOfBirth") || Util.isInteger((String) req.getParameter("dateOfBirth"))) {
                Integer dateOfBirth = Integer.parseInt(req.getParameter("dateOfBirth"));
                if (Validation.validateDateOfBirth(dateOfBirth.intValue())) {
                    ret.put("dateOfBirth", dateOfBirth.intValue());
                } else {
                    message += getProperties().get("en.INVALID_DATEOFBIRTH");
                }
            } else {

            }

            if (null != req.getParameter("mobile")) {
                String mobile = (String) req.getParameter("mobile");
                if (Validation.validateMobile(mobile)) {
                    ret.put("mobile", mobile);
                } else {
                    message += getProperties().get("en.INVALID_MOBILE");
                }
            } else {

            }

            if (null != req.getParameter("gender") || Util.isShort((String) req.getParameter("gender"))) {
                Short gender = Short.parseShort((String) req.getParameter("gender"));
                ret.put("gender", gender);
            } else {

            }
            if ("".equals(message)) {
                ret.put("STATUS", "SUCCESS");
            } else {
                ret.put("STATUS", "ERROR");
                ret.put("MESSAGE", message);
            }
            return ret;
        } catch (Exception ex) {
            ret.put("STATUS", "ERROR");
            ret.put("MESSAGE", ex.toString());
            _Logger.error("validate profile " + ex.toString());
        }
        return ret;
    }

    private Map<String, Object> validateProfile(String jsonData) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(jsonData);
            JSONObject jsonObject = (JSONObject) obj;
            Profile profile = new Profile();
            String message = "";

            if (null != jsonObject.get("displayName")) {
                String displayName = (String) jsonObject.get("displayName");
                if (Validation.validateDisplayName(displayName)) {
                    profile.setDisplayName(displayName);
                } else {
                    message += getProperties().get("en.INVALID_DISPLAYNAME");
                }
            } else {
                message += getProperties().get("en.INVALID_DISPLAYNAME");
            }

            if (null != jsonObject.get("email")) {
                String email = (String) jsonObject.get("email");
                if (Validation.validateEmail(email)) {
                    profile.setEmail(email);
                } else {
                    message += getProperties().get("en.INVALID_EMAIL");
                }
            } else {
                message += getProperties().get("en.INVALID_EMAIL");
            }

            if (null != jsonObject.get("cityId") || Util.isShort((String) jsonObject.get("cityId"))) {
                profile.setCityId(Short.parseShort((String) jsonObject.get("cityId")));
            } else {

            }

            if (null != jsonObject.get("dateOfBirth") || Util.isInteger((String) jsonObject.get("dateOfBirth"))) {
                Long dateOfBirth = (Long) jsonObject.get("dateOfBirth");
                if (Validation.validateDateOfBirth(dateOfBirth.intValue())) {
                    profile.setDateOfBirth(dateOfBirth.intValue());
                } else {
                    message += getProperties().get("en.INVALID_DATEOFBIRTH");
                }
            } else {
                message += getProperties().get("en.INVALID_DATEOFBIRTH");
            }

            if (null != jsonObject.get("mobile")) {
                String mobile = (String) jsonObject.get("mobile");
                if (Validation.validateMobile(mobile)) {
                    profile.setMobileNumber(mobile);
                } else {
                    message += getProperties().get("en.INVALID_MOBILE");
                }
            } else {
                message += getProperties().get("en.INVALID_MOBILE");
            }

            if (null != jsonObject.get("gender") || Util.isShort((String) jsonObject.get("gender"))) {
                Short gender = Short.parseShort((String) jsonObject.get("gender"));
                profile.setGender(GENDER.findByValue(gender));
            } else {

            }
            if ("".equals(message)) {
                ret.put("STATUS", "SUCCESS");
                ret.put("MESSAGE", profile);
            } else {
                ret.put("STATUS", "ERROR");
                ret.put("MESSAGE", message);
            }
            return ret;
        } catch (Exception ex) {
            ret.put("STATUS", "ERROR");
            ret.put("MESSAGE", ex.toString());
            _Logger.error("validate profile " + ex.toString());
        }
        return ret;
    }

}
